package com.yuan.Controller.user;

import com.yuan.Service.AddressBookService;
import com.yuan.context.BaseContext;
import com.yuan.entity.AddressBook;
import com.yuan.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Slf4j
@RequiredArgsConstructor
@Tag(name = "C端地址簿接口")
public class AddressBookController {


    private final AddressBookService addressBookService;

    //查询当前登录用户的所有地址信息
    @GetMapping("/list")
    @Operation(description = "查询当前登录用户的所有地址信息")
    public Result<List<AddressBook>> list() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.listSelf(addressBook);
        return Result.success(list);
    }


    //新增地址
    @PostMapping
    @Operation(description = "新增地址")
    public Result add(@RequestBody AddressBook addressBook) {

        addressBookService.addSelf(addressBook);
        return Result.success();


    }


    //根据id查询
    @GetMapping("/{id}")
    @Operation(description = "根据id查询地址")
    public Result<AddressBook> getById(@PathVariable Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        return Result.success(addressBook);
    }
    @PutMapping
    @Operation(description = "根据id修改地址")
    public Result update(@RequestBody AddressBook addressBook) {
        addressBookService.updateById(addressBook);
        return Result.success();
    }

   //设置默认地址
   @PutMapping("/default")
   @Operation(description = "设置默认地址")
   public Result setDefault(@RequestBody AddressBook addressBook) {
       addressBookService.setDefault(addressBook);
       return Result.success();
   }


    @DeleteMapping
    @Operation(description = "根据id删除地址")
    public Result deleteById(Long id) {
        addressBookService.removeById(id);
        return Result.success();
    }

   //查询默认地址
   @GetMapping("default")
   @Operation(description = "查询默认地址")
   public Result<AddressBook> getDefault() {

       AddressBook addressBook = new AddressBook();
       addressBook.setIsDefault(1);
       addressBook.setUserId(BaseContext.getCurrentId());
       List<AddressBook> list = addressBookService.listSelf(addressBook);
       if (list != null && list.size() == 1) {
           return Result.success(list.get(0));
       }

       return Result.error("没有查询到默认地址");

   }



}
